﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using OpenTK;

namespace Clandestine
{
    public enum Key
    {
        Up = OpenTK.Input.Key.Up,
        Left = OpenTK.Input.Key.Left,
        Down = OpenTK.Input.Key.Down,
        Right = OpenTK.Input.Key.Right,
        Select = OpenTK.Input.Key.Enter, 
        Menu = OpenTK.Input.Key.Escape,
        Cancel = OpenTK.Input.Key.Space,
        Quit = OpenTK.Input.Key.Q
    }

    public delegate void KeyEventDelegate(Key Key);

    public static class Keyboard
    {
        public static event KeyEventDelegate KeyDown;
        public static event KeyEventDelegate KeyUp;

        // Not sure how big the array should be.
        private static bool[] keys = new bool[65536];

        public static bool IsPressed(Key Key)
        {
            // This is the ONLY real bit of value we're adding to KeyboardDevice! :(
            return keys[(int)Key];
        }

        /// <summary>
        /// Call Graphics.Initialise() before this.
        /// </summary>
        public static void Initialise()
        {
            Debug.Assert(Graphics.Manager is OpenTkManager);
            GameWindow gw = ((OpenTkManager)Graphics.Manager).GameWindow;
            Debug.Assert(gw.Keyboard != null); // null if they don't have a keyboard :(
            
            gw.Keyboard.KeyRepeat = false;
            gw.Keyboard.KeyDown += new EventHandler<OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyDown);
            gw.Keyboard.KeyUp += new EventHandler<OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyUp);
        }

        private static void Keyboard_KeyUp(object sender, OpenTK.Input.KeyboardKeyEventArgs e)
        {
            keys[(int)e.Key] = false;

            if (KeyUp != null)
                KeyUp((Key)e.Key);
        }

        private static void Keyboard_KeyDown(object sender, OpenTK.Input.KeyboardKeyEventArgs e)
        {
            keys[(int)e.Key] = true;

            if (KeyDown != null)
                KeyDown((Key)e.Key);
        }

        public static void Deinitialise()
        {
        }
    }
}
